__author__ = 'jiangjun'
__date__ = '2018/4/16 下午7:19'

import requests
import json
import time

from .api_list import ApiList
import dingding.account_info as AccountInfo
from utils.file_utils import FileUtils
from .dd_response_code import DdRetCodeEnum

# 调整到1小时50分钟
CACHE_TIME = 110 * 60

COM_TOKEN_INFO = 'com_token_info'
COM_TICKET_INFO = 'com_ticket_info'


def get_access_token():
    """
    获取钉钉access_token
    :return:
    """
    access_token = ''
    current_time = int(time.time())
    data_json = FileUtils.get_value(file_name=COM_TOKEN_INFO)
    if data_json is None or current_time - int(data_json['begin_time']) >= CACHE_TIME:
        request_url = ApiList.ACCESS_TOKEN.value.format(corp_id=AccountInfo.CORP_ID,
                                                        corp_secret=AccountInfo.CORP_SECRET)
        try:
            response = requests.get(request_url)
            if response.status_code == requests.codes.ok:
                response_json = response.json()
                print('返回获取access_token数据：%s' % response_json)
                if response_json['errcode'] == DdRetCodeEnum.SUCCESS.value:
                    access_token = response_json['access_token']
                    data = {
                        'access_token': access_token,
                        'begin_time': current_time
                    }
                    json_content = json.dumps(data)
                    FileUtils.set_value(file_name=COM_TOKEN_INFO, json_content=json_content)
                    print('token本地不存在！重新获取token：%s' % access_token)
            else:
                print('获取access_token数据失败！status_code：%s, response_json: %s' % (response.status_code, response.json()))
        except Exception as e:
            print('Got a Exception:', e)
            return None
    else:
        access_token = data_json['access_token']
        print('token本地已存在：%s' % access_token)
    return access_token


def get_jsapi_ticket(access_token):
    """
    获取jsapi_ticket
    :param access_token: 获取ticket信息的token参数
    :return:
    """
    ticket = ''
    current_time = int(time.time())
    data_json = FileUtils.get_value(file_name=COM_TICKET_INFO)
    if data_json is None or current_time - int(data_json['begin_time']) >= CACHE_TIME:
        request_url = ApiList.JSAPI_TICKET.value.format(access_token=access_token)
        try:
            response = requests.get(request_url)
            if response.status_code == requests.codes.ok:
                response_json = response.json()
                print('返回获取ticket数据：%s' % response_json)
                if response_json['errcode'] == DdRetCodeEnum.SUCCESS.value:
                    ticket = response_json['ticket']
                    data = {
                        'ticket': ticket,
                        'begin_time': current_time
                    }
                    json_content = json.dumps(data)
                    FileUtils.set_value(file_name=COM_TICKET_INFO, json_content=json_content)
        except Exception as e:
            print('Got a Exception:', e)
            return None
    else:
        ticket = data_json['ticket']
    return ticket


def test_save_file():
    current_time = int(time.time())
    data = {
        'access_token': '11c6cc8ec0333eb5a738ca1a98d48b70',
        'begin_time': current_time
    }
    json_content = json.dumps(data)
    FileUtils.set_value(file_name=COM_TOKEN_INFO, json_content=json_content)


def test_get_file():
    data_json = FileUtils.get_value(file_name=COM_TOKEN_INFO)
    if data_json:
        print(data_json['access_token'])
        print(data_json['begin_time'])
        current_time = int(time.time())
        time_span = current_time - int(data_json['begin_time'])
        print(time_span)


def get_user_id(auth_code):
    """
    通过CODE换取用户身份
    :param access_token:
    :param auth_code:
    :return:
    """
    access_token = get_access_token()
    if not access_token:
        return None
    request_url = ApiList.GET_USER_INFO.value.format(access_token=access_token, auth_code=auth_code)
    try:
        response = requests.get(request_url)
        if response.status_code == requests.codes.ok:
            response_json = response.json()
            print('返回用户标识信息数据：%s' % response_json)
            if response_json['errcode'] == DdRetCodeEnum.SUCCESS.value:
                user_id = response_json['userid']
                return user_id
    except Exception as e:
        print('Got a Exception:', e)
        return None


def get_user_detail(user_id):
    """
    通过userId获取用户详情
    :param user_id:
    :return:
    """
    access_token = get_access_token()
    if not access_token:
        return None
    request_url = ApiList.GET_USER_DETAIL.value.format(access_token=access_token, user_id=user_id)
    try:
        response = requests.get(request_url)
        if response.status_code == requests.codes.ok:
            response_json = response.json()
            print('返回用户详细信息：%s' % response_json)
            if response_json['errcode'] == DdRetCodeEnum.SUCCESS.value:
                userid = response_json['userid']
                name = response_json['name']
                tel = response_json['tel']
                mobile = response_json['mobile']
                email = response_json['email']
                unionid = response_json['unionid']
                dingId = response_json['dingId']
                position = response_json['position']
                avatar = response_json['avatar']
                data = {
                    'userid': userid,
                    'name': name,
                    'tel': tel,
                    'mobile': mobile,
                    'email': email,
                    'dingId': dingId,
                    'unionid': unionid,
                    'position': position,
                    'avatar': avatar
                }
                # json_content = json.dumps(data)
                return data
    except Exception as e:
        print('Got a Exception:', e)
        return None
